<template>
  <Modal
    title="用户详情"
    size="lg"
    @close="$emit('close')"
  >
    <div class="space-y-6">
      <!-- 基本信息 -->
      <div class="bg-gray-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="flex items-center space-x-4">
            <img
              :src="user.avatar || `https://via.placeholder.com/64x64/3b82f6/ffffff?text=${user.username.charAt(0)}`"
              :alt="user.username"
              class="w-16 h-16 rounded-full object-cover"
            >
            <div>
              <h4 class="text-xl font-semibold text-gray-900">{{ user.username }}</h4>
              <p class="text-gray-600">{{ user.email }}</p>
            </div>
          </div>
          <div class="space-y-2">
            <div class="flex justify-between">
              <span class="text-sm font-medium text-gray-500">状态:</span>
              <span
                :class="[
                  'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                  user.status === 'active' 
                    ? 'bg-green-100 text-green-800' 
                    : 'bg-red-100 text-red-800'
                ]"
              >
                {{ user.status === 'active' ? '激活' : '禁用' }}
              </span>
            </div>
            <div class="flex justify-between">
              <span class="text-sm font-medium text-gray-500">创建时间:</span>
              <span class="text-sm text-gray-900">{{ formatDate(user.created_at) }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-sm font-medium text-gray-500">更新时间:</span>
              <span class="text-sm text-gray-900">{{ formatDate(user.updated_at) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 角色信息 -->
      <div class="bg-gray-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">角色权限</h3>
        <div class="space-y-3">
          <div>
            <span class="text-sm font-medium text-gray-500">分配角色:</span>
            <div class="mt-2 flex flex-wrap gap-2">
              <span
                v-for="role in user.roles"
                :key="role"
                class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800"
              >
                <i class="w-4 h-4 mr-1 mdi:account-group" />
                {{ role }}
              </span>
            </div>
          </div>
          
          <!-- 权限列表 -->
          <div v-if="userPermissions.length > 0">
            <span class="text-sm font-medium text-gray-500">拥有权限:</span>
            <div class="mt-2 grid grid-cols-1 md:grid-cols-2 gap-2">
              <div
                v-for="permission in userPermissions"
                :key="permission"
                class="flex items-center text-sm text-gray-700"
              >
                <i class="w-4 h-4 mr-2 text-green-500 mdi:check-circle" />
                {{ permission }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 活动记录 -->
      <div class="bg-gray-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">最近活动</h3>
        <div class="space-y-3">
          <div
            v-for="activity in recentActivities"
            :key="activity.id"
            class="flex items-start space-x-3 p-3 bg-white rounded-lg border"
          >
            <div
              :class="[
                'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center',
                getActivityIconClass(activity.type)
              ]"
            >
              <i :class="getActivityIcon(activity.type)" class="w-4 h-4" />
            </div>
            <div class="flex-1 min-w-0">
              <p class="text-sm font-medium text-gray-900">
                {{ activity.title }}
              </p>
              <p class="text-sm text-gray-500">
                {{ activity.description }}
              </p>
              <p class="text-xs text-gray-400 mt-1">
                {{ formatDateTime(activity.created_at) }}
              </p>
            </div>
          </div>
          
          <div v-if="recentActivities.length === 0" class="text-center py-4">
            <i class="w-12 h-12 mx-auto text-gray-400 mdi:history" />
            <p class="mt-2 text-sm text-gray-500">暂无活动记录</p>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="bg-gray-50 rounded-lg p-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">统计信息</h3>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div class="text-center">
            <div class="text-2xl font-bold text-blue-600">{{ userStats.loginCount }}</div>
            <div class="text-sm text-gray-500">登录次数</div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold text-green-600">{{ userStats.lastLoginDays }}</div>
            <div class="text-sm text-gray-500">天前登录</div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold text-purple-600">{{ userStats.operationCount }}</div>
            <div class="text-sm text-gray-500">操作次数</div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold text-orange-600">{{ userStats.onlineHours }}</div>
            <div class="text-sm text-gray-500">在线时长(h)</div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end">
        <button
          @click="$emit('close')"
          class="btn-secondary"
        >
          关闭
        </button>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Modal from '@/components/Modal.vue'

interface User {
  id: string
  username: string
  email: string
  avatar?: string
  roles: string[]
  status: 'active' | 'inactive'
  created_at: string
  updated_at: string
}

interface Activity {
  id: string
  type: 'login' | 'logout' | 'create' | 'update' | 'delete'
  title: string
  description: string
  created_at: string
}

interface UserStats {
  loginCount: number
  lastLoginDays: number
  operationCount: number
  onlineHours: number
}

interface Props {
  user: User
}

const props = defineProps<Props>()
const emit = defineEmits<{
  close: []
}>()

const userPermissions = ref<string[]>([])
const recentActivities = ref<Activity[]>([])
const userStats = ref<UserStats>({
  loginCount: 0,
  lastLoginDays: 0,
  operationCount: 0,
  onlineHours: 0
})

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取活动图标
const getActivityIcon = (type: string) => {
  const iconMap = {
    login: 'mdi:login',
    logout: 'mdi:logout',
    create: 'mdi:plus-circle',
    update: 'mdi:pencil-circle',
    delete: 'mdi:delete-circle'
  }
  return iconMap[type] || 'mdi:information'
}

// 获取活动图标样式
const getActivityIconClass = (type: string) => {
  const classMap = {
    login: 'bg-green-100 text-green-600',
    logout: 'bg-gray-100 text-gray-600',
    create: 'bg-blue-100 text-blue-600',
    update: 'bg-yellow-100 text-yellow-600',
    delete: 'bg-red-100 text-red-600'
  }
  return classMap[type] || 'bg-gray-100 text-gray-600'
}

// 加载用户详细数据
const loadUserDetails = async () => {
  try {
    // 模拟API调用加载用户权限
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 根据角色模拟权限
    const rolePermissions = {
      '超级管理员': [
        '用户管理', '角色管理', '权限管理', '系统设置',
        '数据导出', '日志查看', '系统监控'
      ],
      '管理员': [
        '用户管理', '角色管理', '数据导出', '日志查看'
      ],
      '普通用户': [
        '个人资料', '密码修改'
      ]
    }
    
    const permissions = new Set<string>()
    props.user.roles.forEach(role => {
      const rolePerms = rolePermissions[role] || []
      rolePerms.forEach(perm => permissions.add(perm))
    })
    userPermissions.value = Array.from(permissions)

    // 模拟活动记录
    recentActivities.value = [
      {
        id: '1',
        type: 'login',
        title: '用户登录',
        description: '从 192.168.1.100 登录系统',
        created_at: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
      },
      {
        id: '2',
        type: 'update',
        title: '更新资料',
        description: '修改了个人头像',
        created_at: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
      },
      {
        id: '3',
        type: 'create',
        title: '创建用户',
        description: '创建了新用户 "test001"',
        created_at: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString()
      }
    ]

    // 模拟统计数据
    userStats.value = {
      loginCount: Math.floor(Math.random() * 100) + 50,
      lastLoginDays: Math.floor(Math.random() * 7),
      operationCount: Math.floor(Math.random() * 500) + 100,
      onlineHours: Math.floor(Math.random() * 100) + 20
    }
  } catch (error) {
    console.error('加载用户详情失败:', error)
  }
}

onMounted(() => {
  loadUserDetails()
})
</script>